package sql

import (
	"fmt"

	"github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"

	"go-papers/tools/config"
)

var (
	configs = map[string]config.Mysql{}
)

func Init() {
	for _, v := range config.GConfig.Mysql {
		configs[v.Name] = v
	}
}

func connect(name string, c config.MysqlConfig) (*DB, error) {
	db := &DB{}
	db.connConfig, _ = mysql.ParseDSN(c.DSN)
	db.maxOpenConns = c.MaxOpenConns
	db.maxIdleConns = c.MaxIdleConns
	db.maxLifeTimeout = c.MaxLifeTimeout

	dbx, err := sqlx.Open("mysql", c.DSN)
	if err != nil {
		panic(fmt.Errorf("get mysql error  %s, dsn: %s, err: %s", name, c.DSN, err.Error()))
	}
	db.DB = dbx
	return db, err
}

func New(name string) *Client {
	c, ok := configs[name]
	if !ok {
		panic(fmt.Errorf("mysql no such config section: %s", name))
	}

	var (
		masterDB *DB
		slaveDB  *DB
	)
	masterDB, _ = connect(name, c.Master)
	if c.Slave.DSN == "" {
		c.Slave.DSN = c.Master.DSN
		slaveDB = masterDB
	} else {
		slaveDB, _ = connect(name, c.Slave)
	}

	cli := &Client{}
	cli.name = name
	cli.masterDB = masterDB
	cli.slaveDB = slaveDB
	cli.master = &Client{}
	cli.master.name = name
	cli.master.masterDB = masterDB
	cli.master.slaveDB = masterDB
	cli.dns = c.Master.DSN
	cli.driver = c.Master.Driver

	dc, _ := mysql.ParseDSN(c.Master.DSN)
	cli.host = dc.Addr
	cli.db = dc.DBName

	return cli
}
